/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment/moment';
import { Card, Row, Col, Form, Select, Button, Spin } from 'antd';
import StandardTable from '@/components/StandardTable';
import DataSet from '@antv/data-set';
import { getLStorage } from '@/utils/utils';
import Charts from './Charts';
import Pies from './Pies';

const { Option } = Select;
const FormItem = Form.Item;
@connect(({ loading, list, setting, user }) => ({
  list,
  // loading: loading.effects['list/getPostList'],
  storageList: loading.effects['list/storageList'],
  smsList: loading.effects['list/smsList'],
  orderList: loading.effects['list/orderList'],
  dakFansEverydayStat: loading.effects['list/dakFansEverydayStat'],
  userKey: setting.options.key,
  userInfo: user.currentUser.user_info,
}))
@Form.create()
export default class StatisticalData extends Component {
  state = {
    currentStation: null,
    canvesSummary: null,
  };

  handleStandardTableChange = pagination => {
    const { dispatch, listType, dataPoints, chartType, userKey, userInfo = {} } = this.props;
    const { phone, inn_area_ids = [], area_ids } = userInfo;
    const cacheAreaId = getLStorage(`KB_INN_AREA_${phone}`);
    const isCompany = area_ids == '*';
    // 防止片区被关闭，导致请求带上上一个的片区ID
    const area_id = inn_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : inn_area_ids.join(',');

    const reqZoneId = userKey === 'yz' ? area_id : null;
    this.getFormValues(res => {
      if (chartType == '2') {
        const params = {
          page: pagination.current,
          page_num: pagination.pageSize,
          brand: res.brand,
          cm_id: dataPoints.inn_id || dataPoints.dak_id,
          start: dataPoints.start,
          end: dataPoints.end,
          area_id: reqZoneId,
        };
        dispatch({
          type: `list/${listType}`,
          payload: params,
        });
      } else {
        const params = {
          page: pagination.current,
          page_num: pagination.pageSize,
          brand: res.brand,
          cm_id: dataPoints.inn_id || dataPoints.dak_id,
          start: dataPoints.start,
          end: dataPoints.end,
          type: 'brand',
          area_id: reqZoneId,
        };
        dispatch({
          type: `list/${listType}`,
          payload: params,
        });
      }
    });
  };

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.start_at = start;
        values.end_at = end;
        delete values.date;
      }
      then(values);
    });
  };

  handleChange = value => {
    const { dispatch, dataPoints, title, userKey, userInfo } = this.props;
    const { phone, inn_area_ids = [], area_ids } = userInfo;
    const cacheAreaId = getLStorage(`KB_INN_AREA_${phone}`);
    const isCompany = area_ids == '*';
    // 防止片区被关闭，导致请求带上上一个的片区ID
    const area_id = inn_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : inn_area_ids.join(',');
    const reqZoneId = userKey === 'yz' ? area_id : null;
    if (title == '出入库分日数据') {
      dispatch({
        type: 'list/storageList',
        payload: {
          brand: value,
          cm_id: dataPoints.inn_id,
          start: dataPoints.start,
          end: dataPoints.end,
          area_id: reqZoneId,
        },
      });

      dispatch({
        type: 'list/storageSummary',
        payload: {
          brand: value,
          cm_id: dataPoints.inn_id,
          start: dataPoints.start,
          end: dataPoints.end,
          area_id: reqZoneId,
        },
        then: data => {
          if (data) {
            this.setState({
              canvesSummary: data,
            });
          } else {
            this.setState({
              canvesSummary: null,
            });
          }
        },
      });
    } else if (title == '订单分日数据') {
      dispatch({
        type: 'list/orderList',
        payload: {
          brand: value,
          cm_id: dataPoints.inn_id,
          start: dataPoints.start,
          end: dataPoints.end,
          area_id: reqZoneId,
        },
      });

      dispatch({
        type: 'list/orderSummary',
        payload: {
          brand: value,
          cm_id: dataPoints.inn_id,
          start: dataPoints.start,
          end: dataPoints.end,
          area_id: reqZoneId,
        },
        then: data => {
          if (data) {
            this.setState({
              canvesSummary: data,
            });
          } else {
            this.setState({
              canvesSummary: null,
            });
          }
        },
      });
    }
  };

  // 品牌下拉
  onGetOperatorList = () => {
    const { dispatch } = this.props;
    const { currentStation, operator } = this.state;
    const { list } = operator || {};
    const { code } = currentStation || { code: '0' };
    if (list) return;
    const shop_id = code == '0' ? '' : code;
    dispatch({
      type: 'list/getBrandsList',
      payload: {
        shop_id,
      },
      then: () => {},
    });
  };

  render() {
    const { canvesSummary } = this.state;
    const {
      data,
      canvesList,
      columns,
      dataPoints,
      between,
      chartType,
      operatoring,
      dropList,
      title,
      titlePieLeft,
      titlePieRight,
      dvs,
      storageList,
      smsList,
      orderList,
      dakFansEverydayStat,
      list,
      listType,
      form: { getFieldDecorator },
    } = this.props;
    const { piesList, orderPic } = list;
    const canvesLists = canvesSummary || canvesList;
    const legendType = {
      in_num: '入库数',
      out_num: '出库数',
      back_num: '退回数',
      sms_num: '短信数',
      num: '订单',
      real_num: '实名订单',
      new_add: '新增粉丝',
      total: '累计粉丝',
    };
    const ds = new DataSet();
    const dv = ds.createView().source(canvesLists);
    if (dvs == '1') {
      dv.transform({
        type: 'fold',
        fields: ['in_num', 'out_num', 'back_num'],
        // 展开字段集
        key: 'city',
        // key字段
        value: 'temperature', // value字段
      });
    } else if (dvs == '2') {
      dv.transform({
        type: 'fold',
        fields: ['sms_num'],
        // 展开字段集
        key: 'city',
        // key字段
        value: 'temperature', // value字段
      });
    } else if (dvs == '3') {
      dv.transform({
        type: 'fold',
        fields: ['num', 'real_num'],
        // 展开字段集
        key: 'city',
        // key字段
        value: 'temperature', // value字段
      });
    } else if (dvs == '4') {
      dv.transform({
        type: 'fold',
        fields: ['new_add', 'total'],
        // 展开字段集
        key: 'city',
        // key字段
        value: 'temperature', // value字段
      });
    }
    const cols = {
      // date: {
      //   range: [0, 1]
      // }
    };
    const colsSmsSummary = {
      // date: {
      //   range: [0, 1]
      // },
      // temperature: {
      //   tickInterval: 5
      // }
    };
    return (
      <div>
        <div>
          <h2>{title}</h2>
          <Form>
            <Row>
              <Col xs={24} sm={24} md={24} lg={12} xl={8} style={{ marginBottom: '10px' }}>
                <span>
                  所选日期：
                  {dataPoints.start}到{dataPoints.end}
                </span>
              </Col>
              <Col xs={24} sm={24} md={24} lg={12} xl={6} style={{ marginBottom: '10px' }}>
                <span>
                  所选驿站：
                  {dataPoints.inn_name ? dataPoints.inn_name : dataPoints.dak_name}
                </span>
              </Col>
              {between == '1' ? (
                <Col xs={24} sm={24} md={24} lg={12} xl={6} style={{ marginBottom: '10px' }}>
                  <FormItem>
                    {getFieldDecorator('brand', {
                      initialValue: dataPoints.brand,
                    })(
                      <Select
                        onFocus={this.onGetOperatorList}
                        filterOption={this.onFilterOperator}
                        onPopupScroll={this.onScrollOperator}
                        showSearch
                        allowClear
                        placeholder="请选择品牌"
                        onChange={this.handleChange}
                        style={{ width: 150 }}
                      >
                        {operatoring ? (
                          <Option disabled value="loading">
                            <Spin />
                          </Option>
                        ) : (
                          <Option key="all" value="all">
                            全部品牌
                          </Option>
                        )}
                        {dropList &&
                          dropList.map(({ brand_en, brand }) => (
                            <Option key={brand_en} value={brand_en}>
                              {brand}
                            </Option>
                          ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
              ) : (
                <Col xl={{ span: 6 }} />
              )}
              <Col xs={24} sm={24} md={24} lg={24} xl={3} style={{ marginBottom: '10px' }}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.props.cancel(false);
                  }}
                >
                  返回
                </Button>
              </Col>
            </Row>
            <Row>
              {chartType == '2' ? (
                <Col>
                  <Card>
                    <Charts
                      canvesList={dv}
                      cols={listType == 'smsList' ? colsSmsSummary : cols}
                      legends={legendType}
                    />
                  </Card>
                </Col>
              ) : (
                <Card>
                  <Col xs={24} sm={24} md={24} lg={12} xl={12} style={{ marginBottom: '10px' }}>
                    <p style={{ textAlign: 'center', fontSize: '18px', fontWeight: '600' }}>
                      {titlePieLeft}
                    </p>
                    {titlePieLeft == '入库品牌统计' ? (
                      <Pies piesList={piesList} numType="in_num" />
                    ) : (
                      <Pies piesList={orderPic} numType="num" />
                    )}
                  </Col>
                  <Col xs={24} sm={24} md={24} lg={12} xl={12} style={{ marginBottom: '10px' }}>
                    <p style={{ textAlign: 'center', fontSize: '18px', fontWeight: '600' }}>
                      {titlePieRight}
                    </p>
                    {titlePieLeft == '入库品牌统计' ? (
                      <Pies piesList={piesList} numType="out_num" />
                    ) : (
                      <Pies piesList={orderPic} numType="real_num" />
                    )}
                  </Col>
                </Card>
              )}
            </Row>
          </Form>
        </div>
        <StandardTable
          rowKey={record => record.id || record.dak_id}
          loading={storageList || smsList || orderList || dakFansEverydayStat}
          data={data}
          columns={columns}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
  }
}
